package com.lpdemilis.pokermanager;

import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Locale;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

public class ConfirmOtherUserActivity extends Activity implements
		MyAsyncListener {
	private int eventid;
	private Event event;
	private User user;
	private int groupindex;
	protected CustomHttpClient client;
	private TextView eventNameTextView;
	private TextView eventTimestartTextView;
	private TextView eventTimeconfirmTextView;
	private TextView eventMaxUsersTextView;
	private TextView eventMinUsersTextView;
	private LinearLayout eventConfirmationLinearLayout;
	private LinearLayout eventConfirmedUsersLinearLayout;
	private LinearLayout eventDisconfirmedUsersLinearLayout;
	private LinearLayout eventUsersLinearLayout;
	protected String SERVER_URL;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_confirmotheruser);

		if (Build.MANUFACTURER.equals("unknown")) {
			SERVER_URL = this.getString(R.string.URL_local);
		} else {
			SERVER_URL = this.getString(R.string.URL);
		}
		
		TextView activityTitleTextView = (TextView) findViewById(R.id.activityTitleTextView);
		Typeface titleTypeface = Typeface.createFromAsset(getAssets(),
                "fonts/POKERPN.TTF");        
        activityTitleTextView.setTypeface(titleTypeface);

		eventid = getIntent().getIntExtra("eventid", 0);
		user = (User) getIntent().getSerializableExtra("user");
		groupindex = getIntent().getIntExtra("groupindex", 0);
		// event = (Event) getIntent().getSerializableExtra("event");

		eventNameTextView = (TextView) findViewById(R.id.eventNameTextView);
		eventTimestartTextView = (TextView) findViewById(R.id.eventTimestartTextView);
		eventTimeconfirmTextView = (TextView) findViewById(R.id.eventTimeconfirmTextView);
		eventMaxUsersTextView = (TextView) findViewById(R.id.eventMaxUsersTextView);
		eventMinUsersTextView = (TextView) findViewById(R.id.eventMinUsersTextView);
		eventConfirmationLinearLayout = (LinearLayout) findViewById(R.id.eventConfirmationLinearLayout);
		eventConfirmedUsersLinearLayout = (LinearLayout) findViewById(R.id.eventConfirmedUsersLinearLayout);
		eventDisconfirmedUsersLinearLayout = (LinearLayout) findViewById(R.id.eventDisconfirmedUsersLinearLayout);
		eventUsersLinearLayout = (LinearLayout) findViewById(R.id.eventUsersLinearLayout);

		getEvent();
	}

	public enum ActionsEnum {
		getEvent, confirmUser, error;
	}

	@Override
	public void executeReturn(String returnValue) {
		String[] returnArray;
		returnArray = returnValue.split("##");

		ActionsEnum action;

		try {
			action = ActionsEnum.valueOf(returnArray[0]);
		} catch (Exception e) {
			action = ActionsEnum.error;
		}

		switch (action) {
		case getEvent:
			getEventReturn(returnArray);
			break;
		case confirmUser:
			confirmUserReturn(returnArray);
			break;
		case error:
			errorReturn(returnArray);
			break;
		}
	}

	private void errorReturn(String[] returnArray) {
		getEvent();
	}

	private void getEventReturn(String[] returnArray) {
		if (returnArray.length <= 1) {

		} else {
			event = new Event();
			event.setId(Integer.parseInt(returnArray[1]));
			event.setName(returnArray[2]);
			event.setDescription(returnArray[3]);
			event.setGroupid(Integer.parseInt(returnArray[4]));
			event.setUserid(Integer.parseInt(returnArray[5]));
			event.setPlace(returnArray[6]);
			Calendar timestart = Calendar.getInstance();
			timestart.setTime(new Date(Long.valueOf(returnArray[7])));
			event.setTimestart(timestart);
			Calendar timeconfirm = Calendar.getInstance();
			timeconfirm.setTime(new Date(Long.valueOf(returnArray[8])));
			event.setTimeconfirm(timeconfirm);
			event.setMaxusers(Integer.parseInt(returnArray[9]));
			event.setMinusers(Integer.parseInt(returnArray[10]));
			event.setRoundtime(Integer.parseInt(returnArray[11]));
			event.setBuyinvalue(Double.valueOf(returnArray[12]));
			event.setRebuyvalue(Double.valueOf(returnArray[13]));
			event.setAddonvalue(Double.valueOf(returnArray[14]));

			String[] prize = returnArray[15].split(",");
			ArrayList<Number> prizeArrayList = new ArrayList<Number>();

			if (!prize[0].equals("")) {
				for (int i = 0; i < prize.length; i++) {
					prizeArrayList.add(Double.valueOf(prize[i]));
				}
			}
			event.setPrize(prizeArrayList);

			String[] point = returnArray[16].split(",");
			ArrayList<Number> pointArrayList = new ArrayList<Number>();

			if (!point[0].equals("")) {
				for (int i = 0; i < point.length; i++) {
					pointArrayList.add(Double.valueOf(point[i]));
				}
			}
			event.setPoint(pointArrayList);

			event.setPrizemod(Integer.parseInt(returnArray[17]));

			String[] blinds = returnArray[18].split(";");

			ArrayList<Number> smallBlindsArrayList = new ArrayList<Number>();
			ArrayList<Number> bigBlindsArrayList = new ArrayList<Number>();

			if (!blinds[0].equals("")) {
				String[] smallBlinds = blinds[0].split(",");
				String[] bigBlinds = blinds[1].split(",");

				for (int i = 0; i < smallBlinds.length; i++) {
					smallBlindsArrayList
							.add(Double.parseDouble(smallBlinds[i]));
					bigBlindsArrayList.add(Double.parseDouble(bigBlinds[i]));
				}
			}

			event.setSmallBlinds(smallBlindsArrayList);
			event.setBigBlinds(bigBlindsArrayList);

			event.setCurrentround(Integer.parseInt(returnArray[19]));
			event.setCurrenttime(Integer.parseInt(returnArray[20]));
			// event.setTotalprize(Double.valueOf(returnArray[21]));
			event.setFinalized(Boolean.valueOf(returnArray[22]));
			Calendar timemodified = Calendar.getInstance();
			timemodified.setTime(new Date(Long.valueOf(returnArray[23])));
			event.setTimemodified(timemodified);

			String[] confirmeduserids = returnArray[24].trim().split(",");

			ArrayList<Number> confirmeduseridsArrayList = new ArrayList<Number>();

			if (!confirmeduserids[0].equals("")) {
				for (int i = 0; i < confirmeduserids.length; i++) {
					confirmeduseridsArrayList.add(Integer
							.valueOf(confirmeduserids[i]));
				}
			}

			event.setConfirmeduseridsArrayList(confirmeduseridsArrayList);

			String[] confirmedusernames = returnArray[25].trim().split(",");

			ArrayList<String> confirmedusernamesArrayList = new ArrayList<String>();

			if (!confirmedusernames[0].equals("")) {
				for (int i = 0; i < confirmedusernames.length; i++) {
					confirmedusernamesArrayList.add(confirmedusernames[i]);
				}
			}

			event.setConfirmedusernamesArrayList(confirmedusernamesArrayList);

			String[] timeconfirmations = returnArray[26].trim().split(",");

			ArrayList<Calendar> timeconfirmationsArrayList = new ArrayList<Calendar>();

			if (!timeconfirmations[0].equals("")) {
				for (int i = 0; i < timeconfirmations.length; i++) {
					Calendar c = Calendar.getInstance();
					c.setTime(new Date(Long.valueOf(timeconfirmations[i])));
					timeconfirmationsArrayList.add(c);
				}
			}

			event.setTimeconfirmationsArrayList(timeconfirmationsArrayList);

			String[] confirmations = returnArray[27].trim().split(",");

			ArrayList<Number> confirmationsArrayList = new ArrayList<Number>();

			if (!confirmations[0].equals("")) {
				for (int i = 0; i < confirmations.length; i++) {
					confirmationsArrayList.add(Integer
							.valueOf(confirmations[i]));
				}
			}

			event.setConfirmationsArrayList(confirmationsArrayList);

			event.setUserCanEdit(Boolean.valueOf(returnArray[28].trim()));

			String[] userids = returnArray[29].trim().split(",");

			ArrayList<Number> useridsArrayList = new ArrayList<Number>();

			if (!userids[0].equals("")) {
				for (int i = 0; i < userids.length; i++) {
					useridsArrayList.add(Integer.valueOf(userids[i]));
				}
			}

			event.setUseridsArrayList(useridsArrayList);

			String[] usernames = returnArray[30].trim().split(",");

			ArrayList<String> usernamesArrayList = new ArrayList<String>();

			if (!usernames[0].equals("")) {
				for (int i = 0; i < usernames.length; i++) {
					usernamesArrayList.add(usernames[i]);
				}
			}

			event.setUsernamesArrayList(usernamesArrayList);

			updateInterface();
		}
	}

	private void confirmUserReturn(String[] returnArray) {
		getEvent();
	}

	private void updateInterface() {
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
				"EEEE, dd/MM/yy, HH:mm", Locale.getDefault());

		// update interface
		eventNameTextView.setText(event.getName());
		eventTimestartTextView.setText(simpleDateFormat.format(event
				.getTimestart().getTime()));
		eventTimeconfirmTextView.setText(simpleDateFormat.format(event
				.getTimeconfirm().getTime()));
		eventMaxUsersTextView.setText(String.valueOf(event.getMaxusers()));
		eventMinUsersTextView.setText(String.valueOf(event.getMinusers()));

		Calendar currenttime = Calendar.getInstance();

		eventConfirmationLinearLayout.removeAllViewsInLayout();
		
		if (event.getTimeconfirm().before(currenttime)) {
			eventTimeconfirmTextView.setTextColor(getResources().getColor(R.color.red_text_color));
			TextView timeconfirmEnded = new TextView(this);
			timeconfirmEnded.setTextColor(getResources().getColor(R.color.red_text_color));			
			timeconfirmEnded.setText(R.string.timeconfirm_ended);
			eventConfirmationLinearLayout.addView(timeconfirmEnded, 0);
		}

		ArrayList<String> confirmedusersArrayList = new ArrayList<String>();

		ArrayList<LinearLayout> confirmedUsersLinearLayouts = new ArrayList<LinearLayout>();
		ArrayList<TextView> confirmedUsersNamesTextViews = new ArrayList<TextView>();
		ArrayList<Button> confirmedUsersButtons = new ArrayList<Button>();

		eventConfirmedUsersLinearLayout.removeAllViewsInLayout();
		eventDisconfirmedUsersLinearLayout.removeAllViewsInLayout();

		for (int i = 0; i < event.getConfirmeduseridsArrayList().size(); i++) {
			confirmedusersArrayList.add(event.getConfirmedusernamesArrayList()
					.get(i));
			confirmedusersArrayList.add(event.getTimeconfirmationsArrayList()
					.get(i).toString());

			confirmedUsersLinearLayouts.add(i, new LinearLayout(this));
			confirmedUsersLinearLayouts.get(i).setLayoutParams(
					new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
							Utils.convertToPixel(60, this)));
			confirmedUsersLinearLayouts.get(i).setGravity(
					Gravity.CENTER_VERTICAL);
			confirmedUsersLinearLayouts.get(i).setPadding(
					Utils.convertToPixel(10, this), 0,
					Utils.convertToPixel(10, this), 0);

			confirmedUsersNamesTextViews.add(i, new TextView(this));
			confirmedUsersNamesTextViews.get(i).setTextAppearance(this,
					R.style.custom_textview);
			confirmedUsersNamesTextViews.get(i).setPadding(0, 0,
					Utils.convertToPixel(10, this), 0);
			confirmedUsersNamesTextViews.get(i).setLayoutParams(
					new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
							LayoutParams.WRAP_CONTENT, (float) 1));

			if ((eventConfirmedUsersLinearLayout.getChildCount() == event
					.getMaxusers())
					&& (event.getConfirmationsArrayList().get(i).equals(1))) {
				confirmedUsersNamesTextViews.get(i).setHint(
						event.getConfirmedusernamesArrayList().get(i));
			} else {
				confirmedUsersNamesTextViews.get(i).setText(
						event.getConfirmedusernamesArrayList().get(i));
			}

			confirmedUsersButtons.add(i,
					Utils.setButtonStyle_sorbus(this, new Button(this)));
			confirmedUsersButtons.get(i).setText(R.string.remove);
			confirmedUsersButtons.get(i).setLayoutParams(
					new LinearLayout.LayoutParams(Utils.convertToPixel(100,
							this), Utils.convertToPixel(40, this)));
			confirmedUsersButtons.get(i).setOnClickListener(
					removeConfirmationButtonClickListener);
			confirmedUsersButtons.get(i).setId(
					event.getConfirmeduseridsArrayList().get(i).intValue());

			confirmedUsersLinearLayouts.get(i).addView(
					confirmedUsersNamesTextViews.get(i));
			confirmedUsersLinearLayouts.get(i).addView(
					confirmedUsersButtons.get(i));

			if (event.getConfirmationsArrayList().get(i).equals(1)) {
				if (eventConfirmedUsersLinearLayout.getChildCount() % 2 == 0) {
					confirmedUsersLinearLayouts.get(i).setBackgroundResource(
							R.drawable.faixa);
				} else {
					confirmedUsersLinearLayouts.get(i).setBackgroundResource(
							R.drawable.faixa1);
				}

				eventConfirmedUsersLinearLayout
						.addView(confirmedUsersLinearLayouts.get(i));
			} else if (event.getConfirmationsArrayList().get(i).equals(0)) {
				if (eventDisconfirmedUsersLinearLayout.getChildCount() % 2 == 0) {
					confirmedUsersLinearLayouts.get(i).setBackgroundResource(
							R.drawable.faixa);
				} else {
					confirmedUsersLinearLayouts.get(i).setBackgroundResource(
							R.drawable.faixa1);
				}

				eventDisconfirmedUsersLinearLayout
						.addView(confirmedUsersLinearLayouts.get(i));
			}
		}
		
		if(eventConfirmedUsersLinearLayout.getChildCount() < event.getMinusers()){
			eventMinUsersTextView.setTextColor(getResources().getColor(R.color.red_text_color));
		}else{
			eventMinUsersTextView.setTextColor(getResources().getColor(R.color.text_color));
		}

		ArrayList<String> usersArrayList = new ArrayList<String>();

		ArrayList<LinearLayout> usersLinearLayouts = new ArrayList<LinearLayout>();
		ArrayList<TextView> usersNamesTextViews = new ArrayList<TextView>();
		ArrayList<Button> confirmUsersButtons = new ArrayList<Button>();
		ArrayList<Button> disconfirmUsersButtons = new ArrayList<Button>();

		eventUsersLinearLayout.removeAllViewsInLayout();

		for (int i = 0; i < event.getUseridsArrayList().size(); i++) {
			usersArrayList.add(event.getUsernamesArrayList().get(i));

			usersLinearLayouts.add(i, new LinearLayout(this));
			usersLinearLayouts.get(i).setLayoutParams(
					new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
							Utils.convertToPixel(60, this)));
			usersLinearLayouts.get(i).setGravity(
					Gravity.CENTER_VERTICAL);
			usersLinearLayouts.get(i).setPadding(
					Utils.convertToPixel(10, this), 0,
					Utils.convertToPixel(10, this), 0);

			usersNamesTextViews.add(i, new TextView(this));
			usersNamesTextViews.get(i).setTextAppearance(this,
					R.style.custom_textview);
			usersNamesTextViews.get(i).setPadding(0, 0,
					Utils.convertToPixel(10, this), 0);
			usersNamesTextViews.get(i).setLayoutParams(
					new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
							LayoutParams.WRAP_CONTENT, (float) 1));
			usersNamesTextViews.get(i).setText(
					event.getUsernamesArrayList().get(i));
			
			usersLinearLayouts.get(i).addView(usersNamesTextViews.get(i));

			confirmUsersButtons.add(i,
					Utils.setButtonStyle_opal(this, new Button(this)));

			confirmUsersButtons.get(i).setLayoutParams(
					new LinearLayout.LayoutParams(Utils
							.convertToPixel(45, this), Utils.convertToPixel(40,
							this)));
			confirmUsersButtons.get(i).setPadding(0, 0, 0, 0);

			Drawable imageConfirm = getResources().getDrawable(
					R.drawable.confirm);
			imageConfirm.setBounds(0, 0, Utils.convertToPixel(45, this),
					Utils.convertToPixel(40, this));
			confirmUsersButtons.get(i).setCompoundDrawables(imageConfirm, null,
					null, null);

			confirmUsersButtons.get(i).setOnClickListener(
					confirmButtonClickListener);
			confirmUsersButtons.get(i).setId(
					event.getUseridsArrayList().get(i).intValue());
			disconfirmUsersButtons.add(i,
					Utils.setButtonStyle_sorbus(this, new Button(this)));

			disconfirmUsersButtons.get(i).setLayoutParams(
					new LinearLayout.LayoutParams(Utils
							.convertToPixel(45, this), Utils.convertToPixel(40,
							this)));
			disconfirmUsersButtons.get(i).setPadding(0, 0, 0, 0);

			Drawable imageDisconfirm = getResources().getDrawable(
					R.drawable.disconfirm);
			imageDisconfirm.setBounds(0, 0, Utils.convertToPixel(45, this),
					Utils.convertToPixel(40, this));
			disconfirmUsersButtons.get(i).setCompoundDrawables(imageDisconfirm,
					null, null, null);

			disconfirmUsersButtons.get(i).setOnClickListener(
					disconfirmButtonClickListener);
			disconfirmUsersButtons.get(i).setId(
					event.getUseridsArrayList().get(i).intValue());

			usersLinearLayouts.get(i).addView(confirmUsersButtons.get(i));
			View spacer1 = new View(this);
			spacer1.setLayoutParams(new LayoutParams(Utils.convertToPixel(10,
					this), Utils.convertToPixel(40, this)));
			usersLinearLayouts.get(i).addView(spacer1);
			usersLinearLayouts.get(i).addView(disconfirmUsersButtons.get(i));

			if (i % 2 == 0) {
				usersLinearLayouts.get(i).setBackgroundResource(
						R.drawable.faixa);
			} else {
				usersLinearLayouts.get(i).setBackgroundResource(
						R.drawable.faixa1);
			}
			
			eventUsersLinearLayout.addView(usersLinearLayouts.get(i));
		}
	}

	@Override
	public void onBackPressed() {
		Intent intent = new Intent(ConfirmOtherUserActivity.this,
				EventActivity.class);
		intent.putExtra("eventid", eventid);
		intent.putExtra("user", user);
		intent.putExtra("groupindex", groupindex);
		ConfirmOtherUserActivity.this.startActivity(intent);
		ConfirmOtherUserActivity.this.finish();
	}

	View.OnClickListener removeConfirmationButtonClickListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			confirmUser(event.getId(), v.getId(), 2, user.getId());
		}
	};

	View.OnClickListener confirmButtonClickListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			confirmUser(event.getId(), v.getId(), 1, user.getId());
		}
	};

	View.OnClickListener disconfirmButtonClickListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			confirmUser(event.getId(), v.getId(), 0, user.getId());

		}
	};

	public void getEvent() {
		try {
			client = new CustomHttpClient(this,
					this.getString(R.string.wait_message), true);
			String action = ActionsEnum.getEvent.toString();
			String paramName1 = "eventid";
			String paramValue1 = String.valueOf(eventid);
			String paramName2 = "userid";
			String paramValue2 = String.valueOf(user.getId());
			client.execute(SERVER_URL, action, paramName1, paramValue1,
					paramName2, paramValue2);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void confirmUser(int eventid, int userid, int presence,
			int usermodified) {
		try {
			client = new CustomHttpClient(this,
					this.getString(R.string.wait_message), true);
			String action = ActionsEnum.confirmUser.toString();
			String paramName1 = "eventid";
			String paramValue1 = String.valueOf(eventid);
			String paramName2 = "userid";
			String paramValue2 = String.valueOf(userid);
			String paramName3 = "presence";
			String paramValue3 = String.valueOf(presence);
			String paramName4 = "usermodified";
			String paramValue4 = String.valueOf(usermodified);
			client.execute(SERVER_URL, action, paramName1, paramValue1,
					paramName2, paramValue2, paramName3, paramValue3,
					paramName4, paramValue4);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.activity_confirmotheruser, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {
		case R.id.menu_logoff:
			Intent intent = new Intent(ConfirmOtherUserActivity.this,
					LoginActivity.class);
			ConfirmOtherUserActivity.this.startActivity(intent);
			ConfirmOtherUserActivity.this.finish();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}
}
